<template>
  <div class="forgot-password-modal-overlay" @click="closeModal">
    <div class="forgot-password-modal" @click.stop>
      <button class="close-btn" @click="closeModal">×</button>

      <h2>找回密码</h2>

      <!-- 步骤1: 输入用户名/邮箱/手机号 -->
      <div v-if="step === 1" class="step-content">
        <form @submit.prevent="handleSendCode" method="post">
          <div class="form-group">
            <label>用户名/邮箱/手机号:</label>
            <input
              v-model="formData.identifier"
              type="text"
              placeholder="请输入用户名、邮箱或手机号"
              required
            >
          </div>

          <div class="form-group">
            <label>验证码:</label>
            <div class="captcha-container">
              <input
                v-model="formData.captcha"
                type="text"
                placeholder="请输入验证码"
                required
                class="captcha-input"
                maxlength="4"
              >
              <div class="captcha-image-wrapper">
                <img
                  v-if="captchaImage"
                  :src="captchaImage"
                  alt="验证码"
                  class="captcha-image"
                  @click="refreshCaptcha"
                  title="点击刷新验证码"
                >
                <div v-else class="captcha-loading">加载中...</div>
              </div>
            </div>
          </div>

          <button type="submit" :disabled="loading" class="submit-btn">
            {{ loading ? '发送中...' : '发送验证码' }}
          </button>
        </form>
      </div>

      <!-- 步骤2: 输入验证码和新密码 -->
      <div v-if="step === 2" class="step-content">
        <div class="info-message">
          <p>验证码已发送到：<strong>{{ maskedContact }}</strong></p>
          <p class="hint">验证码有效期：10分钟</p>
        </div>

        <form @submit.prevent="handleResetPassword" method="post">
          <div class="form-group">
            <label>验证码:</label>
            <input
              v-model="formData.resetCode"
              type="text"
              placeholder="请输入6位数字验证码"
              required
              maxlength="6"
              pattern="[0-9]{6}"
            >
          </div>

          <div class="form-group">
            <label>新密码:</label>
            <input
              v-model="formData.newPassword"
              type="password"
              placeholder="8-20位，包含字母和数字"
              required
              minlength="8"
              maxlength="20"
            >
          </div>

          <div class="form-group">
            <label>确认密码:</label>
            <input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              required
              minlength="8"
              maxlength="20"
            >
          </div>

          <button type="submit" :disabled="loading" class="submit-btn">
            {{ loading ? '重置中...' : '重置密码' }}
          </button>
        </form>

        <div class="back-link">
          <a href="#" @click.prevent="step = 1">返回上一步</a>
        </div>
      </div>

      <!-- 步骤3: 成功提示 -->
      <div v-if="step === 3" class="step-content success-content">
        <div class="success-icon">✓</div>
        <h3>密码重置成功！</h3>
        <p>请使用新密码登录</p>
        <button @click="closeModal" class="submit-btn">返回登录</button>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';
import { encryptPassword } from '@/utils/encryption';

export default {
  name: 'ForgotPasswordModal',
  emits: ['close'],
  data() {
    return {
      step: 1, // 1: 输入信息, 2: 重置密码, 3: 成功
      loading: false,
      captchaImage: '',
      maskedContact: '',
      formData: {
        identifier: '',
        captcha: '',
        resetCode: '',
        newPassword: '',
        confirmPassword: ''
      }
    };
  },
  mounted() {
    this.refreshCaptcha();
  },
  methods: {
    closeModal() {
      this.$emit('close');
      // 重置表单
      this.step = 1;
      this.formData = {
        identifier: '',
        captcha: '',
        resetCode: '',
        newPassword: '',
        confirmPassword: ''
      };
    },

    // 获取验证码
    async refreshCaptcha() {
      try {
        const response = await childEnglishApi.getCaptcha();
        if (response.code === 200 && response.data) {
          this.captchaImage = response.data.image;
          this.formData.captcha = '';
        } else {
          console.error('获取验证码失败:', response.message);
          alert('获取验证码失败，请刷新页面重试');
        }
      } catch (error) {
        console.error('获取验证码错误:', error);
        alert('获取验证码失败: ' + (error.response?.data?.message || error.message));
      }
    },

    // 发送验证码
    async handleSendCode() {
      if (!this.formData.identifier || this.formData.identifier.trim() === '') {
        alert('请输入用户名、邮箱或手机号');
        return;
      }

      if (!this.formData.captcha || this.formData.captcha.trim() === '') {
        alert('请输入验证码');
        return;
      }

      this.loading = true;
      try {
        const response = await childEnglishApi.sendResetCode({
          identifier: this.formData.identifier.trim(),
          captcha: this.formData.captcha.trim()
        });

        if (response.code === 200) {
          // 安全地访问 data.contact，防止 null 错误
          if (response.data && response.data.contact) {
            this.maskedContact = response.data.contact;
          } else {
            this.maskedContact = '***';
          }
          this.step = 2; // 进入下一步
          alert('验证码已发送，请查收');
        } else {
          alert('发送失败: ' + (response.message || '未知错误'));
          this.refreshCaptcha();
        }
      } catch (error) {
        console.error('发送验证码错误:', error);
        const errorMessage = error.response?.data?.message || error.message || '网络错误';
        alert('发送失败: ' + errorMessage);
        this.refreshCaptcha();
      } finally {
        this.loading = false;
      }
    },

    // 重置密码
    async handleResetPassword() {
      if (!this.formData.resetCode || this.formData.resetCode.trim() === '') {
        alert('请输入验证码');
        return;
      }

      if (!this.formData.newPassword || this.formData.newPassword.trim() === '') {
        alert('请输入新密码');
        return;
      }

      if (this.formData.newPassword !== this.formData.confirmPassword) {
        alert('两次密码输入不一致');
        return;
      }

      // 验证密码强度
      const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,20}$/;
      if (!passwordPattern.test(this.formData.newPassword)) {
        alert('密码必须为8-20位，且包含字母和数字');
        return;
      }

      this.loading = true;
      try {
        // 加密新密码
        const encryptedPassword = encryptPassword(this.formData.newPassword);

        const response = await childEnglishApi.resetPassword({
          resetCode: this.formData.resetCode.trim(),
          newPassword: encryptedPassword,
          confirmPassword: encryptedPassword
        });

        if (response.code === 200) {
          this.step = 3; // 显示成功页面
        } else {
          alert('重置失败: ' + response.message);
        }
      } catch (error) {
        const errorMessage = error.response?.data?.message || error.message;
        alert('重置失败: ' + errorMessage);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.forgot-password-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.forgot-password-modal {
  background: white;
  padding: 30px;
  border-radius: 15px;
  width: 450px;
  max-width: 90%;
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 20px;
}

.step-content {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #2c3e50;
  font-weight: bold;
}

.form-group input {
  width: 100%;
  padding: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-group input:focus {
  border-color: #3498db;
  outline: none;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
  margin-top: 10px;
}

.submit-btn:hover:not(:disabled) {
  background: #2980b9;
}

.submit-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input {
  flex: 1;
  width: auto;
}

.captcha-image-wrapper {
  width: 120px;
  height: 40px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
}

.captcha-image-wrapper:hover {
  border-color: #3498db;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}

.captcha-loading {
  color: #999;
  font-size: 12px;
}

.info-message {
  background: #e8f4f8;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
}

.info-message p {
  margin: 5px 0;
  color: #2c3e50;
}

.info-message .hint {
  font-size: 12px;
  color: #7f8c8d;
}

.back-link {
  text-align: center;
  margin-top: 15px;
}

.back-link a {
  color: #3498db;
  text-decoration: none;
  font-size: 14px;
}

.back-link a:hover {
  text-decoration: underline;
}

.success-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #27ae60;
  color: white;
  font-size: 36px;
  line-height: 60px;
  margin: 0 auto 20px;
}

.success-content h3 {
  color: #27ae60;
  margin-bottom: 10px;
}

.success-content p {
  color: #7f8c8d;
  margin-bottom: 20px;
}
</style>

